package com.telecom.restaurant.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.telecom.restaurant.constant.WxConstant;
import com.telecom.restaurant.interceptor.ManageLoginInterceptor;
import com.telecom.restaurant.util.HttpUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * Created by qiqi on 2019/12/18.
 */
@Service
public class WxService {

    Logger logger = LoggerFactory.getLogger(ManageLoginInterceptor.class);

    @Value("#{prop.WX_CORP_ID}")
    private String WX_CORP_ID;

    @Value("#{prop.WX_CORP_SECRET}")
    private String WX_CORP_SECRET;

    LoadingCache<String, String> ACCESS_TOKEN_CACHE = CacheBuilder.newBuilder()
            .initialCapacity(100)
            .maximumSize(10)
            .expireAfterWrite(1, TimeUnit.HOURS)//设置时间对象没有被读/写访问则对象从内存中删除
            //CacheLoader类 实现自动加载
            .build(new CacheLoader<String, String>() {
                @Override
                public String load(String key) {

                    String accessToken = "";
                    try {
                        accessToken = getAccessTokenFromWX();
                        if (accessToken == null) {
                            accessToken = "";
                        }
                    } catch (Exception e) {
                        logger.error("get token error. key:{}", key, e);
                    }
                    return accessToken;
                }
            });


    private String accessTokenKey = "access_token";

    private String wx_token_url = " https://qyapi.weixin.qq.com/cgi-bin/gettoken?";

    private String wx_userId_url = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?";

    private String wx_userInfo_url = "https://qyapi.weixin.qq.com/cgi-bin/user/get?";

    public String getAccessTokenFromCache() {
        try {
            return ACCESS_TOKEN_CACHE.get(accessTokenKey);
        } catch (Exception e) {
            logger.error("get token from cache error.", e);
        }
        return null;
    }


    public String getAccessTokenFromWX() {

        String tokenUrl = wx_token_url + "corpid=" + WX_CORP_ID + "&corpsecret=" + WX_CORP_SECRET;

        String jsonResult = HttpUtil.doHttpsGet(tokenUrl);

        logger.info("get wx access token, url:{}, result:{}", tokenUrl, jsonResult);

        if (StringUtils.isNotBlank(jsonResult)) {

            JSONObject jsonObject = JSON.parseObject(jsonResult);
            String newAccessToken = jsonObject.getString("access_token");
            return newAccessToken;
        }

        return null;
    }


    public String getUserId(String code, int times) {
        String accessToken = getAccessTokenFromCache();
        if (StringUtils.isBlank(accessToken)) {
            return null;
        }

        String userIdUrl = wx_userId_url + "access_token=" + accessToken + "&code=" + code;

        String jsonResult = HttpUtil.doHttpsGet(userIdUrl);

        logger.info("get wx getUserId, times:{}, url:{}, result:{}", times, userIdUrl, jsonResult);

        if (StringUtils.isNotBlank(jsonResult)) {
            JSONObject jsonObject = JSON.parseObject(jsonResult);
            int errorCode = jsonObject.getIntValue("errcode");
            if (WxConstant.SUCCESS_ERROR_CODE == errorCode) {
                String userId = jsonObject.getString("UserId");
                return userId;
            }
            // 重试
            if (WxConstant.INVALID_TOKEN == errorCode && times < 1) {
                ACCESS_TOKEN_CACHE.invalidate(accessTokenKey);
                getUserId(code, times++);
            }
        }

        return null;
    }

    public String getMobile(String userId, int times) {

        String accessToken = getAccessTokenFromCache();
        if (StringUtils.isBlank(accessToken)) {
            return null;
        }

        String userInfoUrl = wx_userInfo_url + "access_token=" + accessToken + "&userid=" + userId;

        String jsonResult = HttpUtil.doHttpsGet(userInfoUrl);

        logger.info("get wx getMobile, url:{}, times:{},result:{}", userInfoUrl, times, jsonResult);

        if (StringUtils.isNotBlank(jsonResult)) {

            JSONObject jsonObject = JSON.parseObject(jsonResult);
            int errorCode = jsonObject.getIntValue("errcode");
            if (WxConstant.SUCCESS_ERROR_CODE == errorCode) {
                String mobile = jsonObject.getString("mobile");
                return mobile;
            }
            // 重试
            if (WxConstant.INVALID_TOKEN == errorCode && times < 1) {
                ACCESS_TOKEN_CACHE.invalidate(accessTokenKey);
                getMobile(userId, times++);
            }
        }

        return null;
    }

}
